package myweb.myhttp;

import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.net.*;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

public class URLConnectionPostTest {

    public static void main(String[] args) throws IOException {
        String urlString = "https://tools.usps.com/go/ZipLookupAction.action";
        Object userAgent = "HTTPie/0.9.2";
        Object redirects = "1";
        CookieHandler.setDefault(new CookieManager(null, CookiePolicy.ACCEPT_ALL));
        HashMap<String, String> param = new HashMap<>();
        param.put("tAddress", "1 Market Stress");
        param.put("tCity", "San Francisco");
        param.put("sState", "CA");
        String result = dopost(new URL(urlString), param,
                userAgent == null ? null : userAgent.toString(),
                redirects == null ? -1 : Integer.parseInt(redirects.toString())
        );
        System.out.println(result);
    }

    private static String dopost(URL url, HashMap<String, String> nameValuePairs, String userAgent, int redirects) throws IOException {
        HttpURLConnection connection = null;
        StringBuilder response = null;
        try {
             connection = (HttpURLConnection) url.openConnection();
            if (connection != null) {
                connection.setRequestProperty("User-Agent", userAgent);
            }
            if (redirects > 0) {
                connection.setInstanceFollowRedirects(false);
            }
            connection.setDoOutput(true);
            // 输出请求参数
            try (PrintWriter out = new PrintWriter(connection.getOutputStream())) {
                boolean first = true;
                //参数必须这样拼接 a=1&b=2&c=5
                for (Map.Entry<String, String> pair : nameValuePairs.entrySet()) {
                    if (first)
                        first = false;
                    else
                        out.println('&');
                    String name = pair.getKey();
                    String value = pair.getValue();
                    out.print(name);
                    out.print('=');
                    //URLEncoder.encode(value,"UTF-8") 当URl中包含特殊字符 需要采用URlEncoder.encode 方法进行转义。
                    out.print(URLEncoder.encode(value, "UTF-8"));
                }
            }
            String encoding = connection.getContentEncoding();
            if (encoding == null) {
                encoding = "UTF-8";
            }
            if (redirects > 0) {
                int responseCode = connection.getResponseCode();
                System.out.println("responseCode:" + responseCode);
                if (responseCode == HttpURLConnection.HTTP_MOVED_PERM
                        || responseCode == HttpURLConnection.HTTP_MOVED_TEMP
                        || responseCode == HttpURLConnection.HTTP_SEE_OTHER) {
                    String location = connection.getHeaderField("Location");
                    if (location != null) {
                        URL base = connection.getURL();
                        connection.disconnect();
                        return dopost(new URL(base, location), nameValuePairs, userAgent, redirects - 1);
                    }
                }
            }
            else if (redirects == 0) {
                throw new IOException("Too many redirects");
            }
            //接下来获取html 内容
             response = new StringBuilder();
            try (Scanner in =new Scanner(connection.getInputStream(),encoding)){
                while (in.hasNextLine()){
                    response.append(in.nextLine());
                    response.append("\n");
                }
            }
        } catch (IOException e) {
            InputStream errorStream = connection.getErrorStream();
            if (errorStream == null) throw e;
            try (Scanner in = new Scanner(errorStream)){
                response.append(in.nextLine());
                response.append("\n");
            }
        }
        return response.toString();
    }
}
